package com.lei.retrofitdemo.network.response;

import com.huluobo.lc.a1803aretrofitrxdemo.network.exception.ApiException;
import com.huluobo.lc.a1803aretrofitrxdemo.network.exception.CustomException;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;

/**
 * @author Lc
 * @description: 用于通用解析, 并抛出异常
 * @date :2020/11/10 14:57
 */
public class ResponseTransformer {
    public static <T> ObservableTransformer<Response<T>, T> handleResult() {
        return upstream -> upstream.onErrorResumeNext(new ErrorResumeFunction<>()).flatMap(new ResponseFunction<>());
    }

    /**
     * 非服务器产生的异常,比如本地无网络请求,Json数据解析错误
     */

    private static class ErrorResumeFunction<T> implements Function<Throwable, ObservableSource<?
            extends Response<T>>> {

        @NonNull
        @Override
        public ObservableSource<? extends Response<T>> apply(@NonNull Throwable throwable) throws Exception {
            return Observable.error(CustomException.handleException(throwable));
        }
    }

    /**
     * 服务器返回的数据解析
     * 正常服务器返回数据和服务器可能返回的异常
     */
    private static class ResponseFunction<T> implements Function<Response<T>, ObservableSource<T>> {

        @NonNull
        @Override
        public ObservableSource<T> apply(@NonNull Response<T> tResponse) throws Exception {
            int code = tResponse.getRet();
            String message = tResponse.getMsg();
            if (code == 200) {
                return Observable.just(tResponse.getData());
            } else {
                return Observable.error(new ApiException(code, message));
            }
        }
    }
}
